<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        img{width:40px;}
    </style>
</head>
<body>
    <h2>这是购物车</h2>
    <a href="./list.html">继续购物</a>
    <table border="1" cellspacing="0" width="800">
        <thead>
            <tr>
                <th>选中</th>
                <th>图片</th>
                <th>名称</th>
                <th>数量</th>
                <th>价格</th>
                <th>小计</th>
                <th>删除</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <td align="right"><input type="checkbox" class="allCheck"></td>
                <td>全选</td>
                <td align="right">总数量</td>
                <td class="allNum">0</td>
                <td align="right">总价</td>
                <td class="allPrice">0</td>
                <td class="removeCheck">删除选中</td>
            </tr>
        </tfoot>
    </table>
</body>
<script src="./js/ajax.js"></script>
<script>

    const tbody = document.querySelector("tbody");

    let goods = localStorage.getItem("goods");
    goods = goods ? JSON.parse(goods) : [];

    const pArr = [];

    // 遍历本地存储中获取到的数据
    // 根据id开启ajax请求
    // 并保存ajax请求开启之后的promise实例
    goods.forEach(val=>{
        pArr.push(ajaxPromise("http://localhost:3000/getDetail?id=" + val.id));
    })

    // 利用Promise的批处理，处理所有请求
    Promise.all(pArr).then(res=>{
        // 因为后端给的数据是json字符，所以解析promise获取到的数据
        const arr = res.map(val=>{
            return JSON.parse(val).data;
        })
        // 最终处理之后的数据
        // console.log(arr);
        // 根据数据，渲染页面
        let str = "";
        arr.forEach((val,idx)=>{
            str += `<tr myid="${val.id}">
                        <td><input type="checkbox" class="check" ${goods[idx].check ? 'checked' : ''}></td>
                        <td><img src="${val.src}"></td>
                        <td>${val.name}</td>
                        <td><input type="number" value="${goods[idx].num}" class="num"></td>
                        <td>${val.price}</td>
                        <td>${val.price * goods[idx].num}</td>
                        <td class="remove">删除</td>
                    </tr>`
        })
        tbody.innerHTML = str
    })

    // ========

    // 修改并记录选中状态
    tbody.addEventListener("change", function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.className.includes("check")){
            const id = target.parentNode.parentNode.getAttribute("myid");
            const check = target.checked;

            let i;
            goods.some((val,idx)=>{
                i = idx;
                return val.id === id
            })

            goods[i].check = check;

            localStorage.setItem("goods", JSON.stringify(goods));

            $(".allCheck").checked = goods.every(val=>val.check);

            // 计算总数量
            $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);

            // 计算总价
            $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);
        }
    })

    // 修改并记录数量
    tbody.addEventListener("change", function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.className.includes("num")){
            const id = target.parentNode.parentNode.getAttribute("myid");
            const num = target.value-0;

            let i;
            goods.some((val,idx)=>{
                i = idx;
                return val.id === id
            })

            goods[i].num = num;

            localStorage.setItem("goods", JSON.stringify(goods));

            // 计算总数量
            $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);

            // 计算总价
            $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);
        }
    })

    // 删除DOM并修改数据
    tbody.addEventListener("click", function(eve){
        const e = eve || window.event;
        const target = e.target || e.srcElement;
        if(target.className.includes("remove")){
            const id = target.parentNode.getAttribute("myid");
            target.parentNode.remove();

            let i;
            goods.some((val,idx)=>{
                i = idx;
                return val.id === id
            })

            goods.splice(i, 1);

            localStorage.setItem("goods", JSON.stringify(goods));

            $(".allCheck").checked = goods.every(val=>val.check);

            // 计算总数量
            $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);

            // 计算总价
            $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);
        }
    })

    // 如果所有商品都被选中了，全选默认选中
    $(".allCheck").checked = goods.every(val=>val.check);

    // 全选按钮影响单个商品的选中
    $(".allCheck").onclick = function(){
        const all = document.querySelectorAll(".check");
        [...all].forEach(val=>{
            val.checked = this.checked;
        })
        goods.forEach(val=>{
            val.check = this.checked;
        })
        localStorage.setItem("goods", JSON.stringify(goods));

        // 计算总数量
        $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);

        // 计算总价
        $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);
    }

    // 计算总数量
    $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);


    // 计算总价
    $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);


    // 删除选中
    $(".removeCheck").onclick = function(){
        goods = goods.filter(val=>!val.check);

        const all = document.querySelectorAll(".check");
        [...all].forEach(val=>{
            if(val.checked){
                val.parentNode.parentNode.remove();
            }
        })

        localStorage.setItem("goods", JSON.stringify(goods));

        // 计算总数量
        $(".allNum").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num : 0), 0);

        // 计算总价
        $(".allPrice").innerHTML = goods.reduce((prev,val)=>prev + (val.check ? val.num*val.price : 0), 0);
    }

    


    function $(s){
        return document.querySelector(s);
    }
</script>
</html>